<?php





namespace app\mini\controller;



// use app\BaseController as BaseController;

use app\mini\model\SendUrlModel;

use think\response\Json;

use think\facade\Db;





class GetAccessToken extends Access

{

    /**

     * 获取小程序access_token

     * @return Json

     * @author hz

     * @create 2022-11-26

     */

    public function get_accesstoken_mini()

    {

        $model = new SendUrlModel();

        // echo "获取access_token";

        $url = "https://api.weixin.qq.com/cgi-bin/token";

        $jsonData = [

            'grant_type' => 'client_credential',

            'appid'      => 'wxfee2f64c9d301f2f',

            'secret'     => '26385eaeace3711d002ba80ec7bd3a0e',

        ];

        $data = $model->send_url($url,$jsonData);

        $fomateToken = json_decode($data,true);

        $fomateToken['expireTime'] = time() + $fomateToken['expires_in'] - 10;

        // echo "<pre>";
        // print_r($fomateToken);
        // echo "</pre>";

        $newData = json_encode($fomateToken);

        file_put_contents('./token_file/accessToken.json', $newData);

        return $newData;

    }

    // 获取公众号的access_token
    public function get_access_token_wx()
    {

        $model = new SendUrlModel();

        $url = "https://api.weixin.qq.com/cgi-bin/token";

        $jsonData = [

            'grant_type' => 'client_credential',

            'appid'      => 'wx7cde54d2bb9607e6',

            'secret'     => '1aa86183eca8d6ebf854cbc0349543df',

        ];

        $data = $model->send_url($url,$jsonData);

        $fomateToken = json_decode($data,true);

        $fomateToken['expireTime'] = time() + $fomateToken['expires_in'] - 10;

        // echo "<pre>";
        // print_r($fomateToken);
        // echo "</pre>";

        $newData = json_encode($fomateToken);

        file_put_contents('./token_file/accessTokenWX.json', $newData);

        return $newData;

    }


    /**
     * 获取URL Link
     * @return Json
     * @author yp
     * @create 2022-11-26

     */

    public function get_url_link(){

        $model = new SendUrlModel();

        $fomateToken = file_get_contents('./token_file/accessToken.json');

        // var_dump($fomateToken);

        $token_info = json_decode($fomateToken,true);

        // echo "<pre>";
        // print_r($token_info);
        // echo "</pre>";
        // exit;

        $nowTime = time();

        if($nowTime < $token_info['expireTime']){

            // echo "直接获取url_link";

            $ACCESS_TOKEN = $token_info['access_token'];

            $URL_Link = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=".$ACCESS_TOKEN;

            $URL_jsonData = [

                'path' => 'pages/questionPaper/questionPaper',

                'query' => 'status=1',

                'expire_type' => 1,

                'expire_interval' => 1,

            ];

            $res = $model->send_url($URL_Link,json_encode($URL_jsonData));

            $result = json_decode($res,true);

            // echo "<pre>";
            // print_r($result);
            // echo "</pre>";
            // exit;
            
            return $res;

        }else{

            // echo "access_token已过期，请重新获取";

            $access_token = $this->get_accesstoken_mini();

            // 重新获取access_token之后再次执行
            $fomateToken = file_get_contents('./token_file/accessToken.json');

            $token_info = json_decode($fomateToken,true);

            $nowTime = time();

            if($nowTime < $token_info['expireTime']){

                $ACCESS_TOKEN = $token_info['access_token'];

                $URL_Link = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=".$ACCESS_TOKEN;

                $URL_jsonData = [

                    'path' => 'pages/questionPaper/questionPaper',

                    'query' => 'status=1',

                    'expire_type' => 1,

                    'expire_interval' => 1,

                ];

                $res = $model->send_url($URL_Link,json_encode($URL_jsonData));

                $result = json_decode($res,true);

                // echo "<pre>";
                // print_r($result);
                // echo "</pre>";
                // exit;
                
                return $res;

            }

        }

    }



    // 客户小程序获取ACCESS_TOKEN
    public function getMiniProjectAccessToken():Json
    {

        $fomateToken = file_get_contents('./token_file/accessToken.json');

        $token_info = json_decode($fomateToken,true);

        // echo "<pre>";
        // print_r($token_info);
        // echo "</pre>";
        // exit;

        $nowTime = time();

        if($nowTime < $token_info['expireTime']){

            return resultArray(['error' => '获取成功', 'data' => $token_info]);

            exit;

        }else{

            $access_token = $this->get_accesstoken_mini();

            return resultArray(['error' => '获取成功', 'data' => $access_token]);

            exit;

        }

    }


    

    /**
     * 获取公众号关注会员的openid集合
     * 通过公众号openid获取unionid
     * 
     * 
     */
    public function get_gzh_fans()
    {
        $model = new SendUrlModel();

        $access_token = $this->get_access_token_wx();

        $token_info = json_decode($access_token,true);

        $ACCESS_TOKEN = $token_info['access_token'];

        $URL_Link = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$ACCESS_TOKEN."&next_openid=orXbIsyOTRO70WxtKXQxKV4wuMJM";

        $URL_jsonData = [];

        $res = $model->send_url($URL_Link,json_encode($URL_jsonData));

        // echo "<pre>";
        // print_r($res);
        // echo "</pre>";
        // exit;

        $data = json_decode($res,true);

        $openIds = $data['data']['openid'];



        // $URL_Link = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$ACCESS_TOKEN}&openid=orXbIs9RDp16tEveSqcWIYB82R6c&lang=zh_CN";

        // $URL_jsonData = [];

        // $res = $model->send_url($URL_Link,json_encode($URL_jsonData));

        // $data = json_decode($res,true);

        // echo "<pre>";
        // print_r($data);
        // echo "</pre>";
        // exit;

        // $openIds = ['orXbIs9RDp16tEveSqcWIYB82R6c'];

        $where = [];

        array_push($where,['openid','in',$openIds]);

        $existingOpenIds = Db::name('wx_gzh_fans')->where($where)->column('openid');

        // echo "<pre>";
        // print_r($existingOpenIds);
        // echo "</pre>";
        // exit;

        $addData = [];

        foreach ($openIds as $key => $value) {

            if(in_array($value,$existingOpenIds)){

            }else{

                // $one = [];

                // $URL_Link = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$ACCESS_TOKEN}&openid={$value}&lang=zh_CN";
    
                // $URL_jsonData = [];
    
                // $res = $model->send_url($URL_Link,json_encode($URL_jsonData));
    
                // $add = json_decode($res,true);
    
                // $one['openid'] = $add['openid'];
    
                // $one['unionid'] = $add['unionid'];
    
                // $one['subscribe_time'] = $add['subscribe_time'];
    
                // $one['subscribe_scene'] = $add['subscribe_scene'];

                $one['openid'] = $value;
    
                array_push($addData,$one);

            }

        }

        echo "<pre>";
        print_r($addData);
        echo "</pre>";
        // exit;

        $res = Db::name("wx_gzh_fans")->insertAll($addData);

    }
    
    /**
     * 通过小程序的openid获取unionid
     * 
     */
    public function get_unionid_bymini(){
        $list = Db::name('wx_gzh_fans')->select()->toArray();

        echo "<pre>";
        print_r($list);
        echo "</pre>";
        exit;
    }

    // 获取顾客转介绍二维码
    public function  getTurnQrCode():Json
    {
        $request = $this->request->param();


        // 请求顾客转介绍小程序二维码

        $fomateToken = file_get_contents('./token_file/accessToken.json');

        $token_info = json_decode($fomateToken,true);

        // echo "<pre>";
        // print_r($token_info);
        // echo "</pre>";
        // exit;

        $nowTime = time();

        if($nowTime < $token_info['expireTime']){

            $ACCESS_TOKEN = $token_info['access_token'];

        }else{

            $access_token = $this->get_accesstoken_mini();

            $ACCESS_TOKEN = $access_token['access_token'];

        }

        $model = new SendUrlModel();

        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$ACCESS_TOKEN;

        $jsonData = [

            'scene'       => 'customer_id='.$request['customer_id'],

            'page'        => 'pages/index/index',

            'check_path'  => false,

            'env_version' => 'develop',

        ];

        $data = $model->send_url($url,$jsonData);

        $res = json_decode($data,true);

        echo '<pre>';
        print_r($res);
        echo '</pre>';
        exit;

    }

}